#!/usr/bin/env python3
"""
从多个可靠来源抓取真实的交易所Logo
"""
import requests
import os
from pathlib import Path
import time

# 使用多个CDN源
LOGO_SOURCES = {
    # 使用cryptocurrency-icons开源项目和其他公开CDN
    'binance': [
        'https://cryptologos.cc/logos/binance-coin-bnb-logo.svg',
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/270.png'
    ],
    'okx': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/294.png',
        'https://cryptologos.cc/logos/okx-okb-logo.svg'
    ],
    'gateio': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/302.png',
    ],
    'bybit': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/521.png',
    ],
    'kucoin': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/311.png',
        'https://cryptologos.cc/logos/kucoin-kcs-logo.svg'
    ],
    'huobi': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/102.png',
    ],
    'kraken': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/24.png',
    ],
    'coinbase': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/89.png',
    ],
    'mexc': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/544.png',
    ],
    'bingx': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/1599.png',
    ],
    'bitget': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/404.png',
    ],
    'bitmart': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/425.png',
    ],
    'bitrue': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/464.png',
    ],
    'bitstamp': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/1.png',
    ],
    'crypto-dot-com': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/37.png',
    ],
    'ascendex': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/459.png',
    ],
    'btcmarkets': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/139.png',
    ],
    'dydx': [
        'https://cryptologos.cc/logos/dydx-dydx-logo.svg',
        'https://s2.coinmarketcap.com/static/img/coins/64x64/28324.png'
    ],
    'hyperliquid': [
        'https://s2.coinmarketcap.com/static/img/coins/64x64/29691.png',
    ],
    'injective': [
        'https://cryptologos.cc/logos/injective-inj-logo.svg',
        'https://s2.coinmarketcap.com/static/img/coins/64x64/7226.png'
    ],
    'ndax': [
        'https://s2.coinmarketcap.com/static/img/exchanges/64x64/728.png',
    ],
    'vertex-protocol': [
        'https://s2.coinmarketcap.com/static/img/coins/64x64/24818.png',
    ],
    'xrp': [
        'https://cryptologos.cc/logos/xrp-xrp-logo.svg',
        'https://s2.coinmarketcap.com/static/img/coins/64x64/52.png'
    ],
}

def download_logo(name, urls, output_dir):
    """尝试从多个URL下载logo"""
    if isinstance(urls, str):
        urls = [urls]
    
    for i, url in enumerate(urls):
        try:
            print(f"正在下载 {name} (尝试 {i+1}/{len(urls)})...")
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
                'Referer': 'https://coinmarketcap.com/'
            }
            response = requests.get(url, headers=headers, timeout=15)
            response.raise_for_status()
            
            # 确定文件扩展名
            content_type = response.headers.get('content-type', '')
            if 'svg' in content_type or url.endswith('.svg'):
                ext = 'svg'
            elif 'png' in content_type or url.endswith('.png'):
                ext = 'png'
            else:
                ext = 'jpg'
            
            # 保存文件
            output_path = output_dir / f"{name}.{ext}"
            with open(output_path, 'wb') as f:
                f.write(response.content)
            
            print(f"✓ {name} 下载完成 ({ext}, {len(response.content)} bytes)")
            time.sleep(0.5)  # 避免请求过快
            return True
        except Exception as e:
            print(f"  ✗ 失败: {e}")
            if i < len(urls) - 1:
                time.sleep(1)
                continue
    
    return False

def main():
    # 设置输出目录
    script_dir = Path(__file__).parent
    project_dir = script_dir.parent
    output_dir = project_dir / 'assets' / 'icons' / 'exchanges'
    output_dir.mkdir(parents=True, exist_ok=True)
    
    print(f"输出目录: {output_dir}")
    print(f"开始下载 {len(LOGO_SOURCES)} 个交易所logo...\n")
    
    success_count = 0
    failed_list = []
    
    for name, urls in LOGO_SOURCES.items():
        if download_logo(name, urls, output_dir):
            success_count += 1
        else:
            failed_list.append(name)
        print()
    
    print(f"完成! 成功下载 {success_count}/{len(LOGO_SOURCES)} 个logo")
    if failed_list:
        print(f"\n未能下载的交易所: {', '.join(failed_list)}")

if __name__ == '__main__':
    main()

